﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Linq;
using SyncList.Business.ValueObject;

namespace SyncList.Business.Services
{

    /// <summary>
    /// Importer les données
    /// </summary>
    class ImportService : IImportService
    {

        private static int AnonymeConstant = 1;

        /// <summary>
        /// Importer Xml
        /// </summary>
        /// <param name="fileName">Nom du fichier à importer</param>
        /// <returns></returns>
        public Data ImportList(string fileName)
        {
            Data data = null;

            if (fileName.EndsWith(".bak")) return (data); // Ignorer pour éviter des bouclages terribles pour un multi-drag'n'drop

            if (File.Exists(fileName))
            {
                data = new Data();
                XDocument xDoc = XDocument.Load(fileName);

                data.Folders.Clear();

                var xDefinitions = from xDef in xDoc.Element("SyncList").Descendants("Definition")
                                  select new
                                  {
                                      PathList = xDef.Element("PathList").Descendants("Path").Select(d => d.Value),
                                      MinSize = xDef.Element("Filter").Attribute("MinSize").Value,
                                      Title = xDef.Element("Title").Value,
                                      UserName = ReadString(xDef, "UserName")
                                  };
                var xDefinition = xDefinitions.FirstOrDefault();
                if (xDefinition != null)
                {
                    data.FileFilter.MinSize = long.Parse(xDefinition.MinSize);                   
                    data.Folders.AddRange(xDefinition.PathList);
                    data.Title = xDefinition.Title;
                    data.UserName = xDefinition.UserName;
                }

                IEnumerable<FileItem> xFiles = from xFile in xDoc.Descendants("File")
                             select new FileItem
                             {
                                   Name = (string)xFile.Attribute("name"),
                                   Size = (long)xFile.Attribute("size"),
                                   Hash = (string)xFile.Attribute("hash"),
                                   LocalFolder = (string)xFile.Attribute("folder")
                             };

                foreach (FileItem file in xFiles)
                    data.Files.Add(file);


                // - Exceptions
                if (String.IsNullOrWhiteSpace(data.UserName))
                {
                    data.UserName = "Anonyme" + AnonymeConstant.ToString();    // <UserName>Emmanuel</UserName> à mettre dans Definition                
                    AnonymeConstant++;
                }


                File.Copy(fileName, fileName + ".lastimport.bak", true);

                data.XmlFileName = fileName;

            }
            
            
            return (data);
        }



        private string ReadString(XElement el, string name)
        {
            string result = "";
            XElement sub = el.Element("UserName");
            if (sub != null)
                result = sub.Value;
            return(result);
        }



        /// <summary>
        /// Import en XML la liste de ce que l'on désire
        /// </summary>
        /// <param name="root">Cible pour inscrire tout ce que l'utilisateur désire</param>
        /// <param name="fileName">Nom du fichier de sauvegarde</param>
        public void ImportWishes(DirectoryContent root, string fileName)
        {
            if (fileName.EndsWith(".bak")) return; // Ignorer pour éviter des bouclages terribles pour un multi-drag'n'drop

            if (File.Exists(fileName))
            {
                
                XDocument xDoc = XDocument.Load(fileName);
                            

                var users = from xUser in xDoc.Element("SyncList").Element("Users").Descendants("User")
                    select xUser;

                root.Clear();

                foreach(XElement xUser in users)
                {
                    string userName = (string)(xUser.Attribute("name"));
       
                    DirectoryContent userDirectory = root.GetDirectory(userName);
                    userDirectory.DirectoryType = DirectoryTypeEnum.User;

                    IEnumerable<FileItem> files = from xFile in xUser.Descendants("File")
                                                   select new FileItem
                                                       {
                                                           Name = (string)xFile.Attribute("name"),
                                                           Size = (long)xFile.Attribute("size"),
                                                           Hash = (string)xFile.Attribute("hash"),
                                                           LocalFolder = (string)xFile.Attribute("folder")
                                                       };




                    // - Placer la demande de fichier
                    foreach (FileItem file in files)
                    {
                        file.UserName = userName;
                        userDirectory.PlaceFileInTree(file, file.LocalFolder);
                    }

                }

             }
            
        }



    }
}
